import React, { useEffect, useState } from "react";
import { useHistory, useLocation } from "react-router-dom/cjs/react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { LOGIN_USER_STATE_REQ_SUCCESS, cleanUserState, getUserState } from "@/store/actions/userState";
import { useFormik } from "formik";
import NavigateBar from "@/components/NavigateBar";
import icon_home_arrow_right from '@/assets/icon_home_arrow_right.png'
import icon_home_arrow_left from '@/assets/icon_home_arrow_left.png'
import icon_home_increase1 from '@/assets/icon_home_increase1.png'
import icon_home_increase2 from '@/assets/icon_home_increase2.png'
import icon_home_increase3 from '@/assets/icon_home_increase3.png'
import icon_home_top_bg from '@/assets/icon_home_top_bg.png'
import icon_home_logo from '@/assets/icon_home_logo.png'
import { DotLoading, Mask } from "antd-mobile";
import { PageTag } from "@/utils/pageTag";
import { saveEvent } from "@/store/actions/saveEvent";
import './loginAd.css';
import '../../App.css'
import '../Proof/proof.css';
import AddToHomeGifDialog from "@/components/AddToHomeGifDialog/AddToHomeGifDialog";
import AddHomeEvent from "@/utils/addHomeEvent";
import { removeUserInfo } from "@/utils/storage";
import { LOGIN_REQ_FAIL, LOGIN_REQ_SUCCESS, cleanLoginState, doLogin } from "@/store/actions/login";
import { SEND_OTP_REQ_FAIL, SEND_OTP_REQ_SUCCESS, cleanOtpState, sendOtp } from "@/store/actions/sendOtp";
import { isLoanLoaning, isLoanReject, isLoanRepayNow, isLoanReviewing } from "@/utils/loanStatus";
import Input from "@/components/Input";
import OtpInput from "@/components/OtpInput";



/**
 * 登录页
 */
export default function LoginAd() {

    //loading状态
    const [maskVisible, setMaskVisible] = useState(false)

    //显示add home弹框
    const [addHomeMaskVisible, setAddHomeMaskVisible] = useState(false);
    const [addHomeMaskIsHomeMode, setAddHomeMaskIsHomeMode] = useState(false);

    //倒计时状态
    const [canStart, setCanStart] = useState(false);

    //需要转登录状态
    const [needToLoginPage, setNeedToLoginPage] = useState(false);

    //需要转注册状态
    const [needToRegisterPage, setNeedToRegisterPage] = useState(false);

    //按键文字
    const [isRegitsterType, setIsRegitsterType] = useState(false);

    //获取Redux Store中的信息
    const sendOtpInfo = useSelector(state => state.sendOtp)

    //获取Redux Store中的信息
    const loginInfo = useSelector(state => state.login)

    //获取Redux Store中的用户状态信息
    const userStateInfo = useSelector(state => state.userState)

    //router
    const history = useHistory()

    const location = useLocation()

    // 获取 Redux 分发器
    const dispatch = useDispatch()

    //清空登录信息
    useEffect(() => {
        console.log("LOGIN-移除登录信息")
        //移除登录信息
        removeUserInfo()

        //清除登录信息
        dispatch(cleanLoginState())
        dispatch(cleanUserState())
        dispatch(cleanOtpState())

        //来源
        const dreferrer = document.referrer || ""
        console.log("document.referrer:==========" + dreferrer)

        //来源参数
        const queryParams = new URLSearchParams(location.search);
        const isRegister = queryParams.get('isRegister') || ""
        if (isRegister === "YES") {
            setIsRegitsterType(true)
        } else {
            setIsRegitsterType(false)
        }

        //打点
        doHitEvent("LOGIN_START")

        return () => {
            //打点
            doHitEvent("LOGIN_END")
        }
    }, [])

    //监听验证码接口返回
    useEffect(() => {
        console.log("Login-监听验证码返回")
        console.log(sendOtpInfo)
        //获取短信发送成功返回
        if (sendOtpInfo.status === SEND_OTP_REQ_SUCCESS) {
            console.log("Login-短信发送成功")
            console.log(sendOtpInfo)
            //关闭loading
            setMaskVisible(false)

            //开始倒计时
            setCanStart(true)

            const directLoginFlag = sendOtpInfo.directLoginFlag || ""
            if (directLoginFlag === "YES") {
                //验证手机号
                let mobile = form.values.mobile

                //验证验证码
                let code = "0000"

                //请求登录
                doOtpLogin(mobile, code, "YES")
            }

        } else if (sendOtpInfo.status === SEND_OTP_REQ_FAIL) {
            //关闭loading
            setMaskVisible(false)

            //判断弹框----暂时关闭
            const otpResCode = sendOtpInfo.resCode || -1
            if (otpResCode === 2001) {
                //需要弹提示--你是新客，需要注册
                setNeedToRegisterPage(true)
                setNeedToLoginPage(false)

            } else if (otpResCode === 2002) {
                //需要弹提示--你是旧客，需要登录
                setNeedToRegisterPage(false)
                setNeedToLoginPage(true)
            }
        }
    }, [sendOtpInfo])

    //监听登录接口返回
    useEffect(() => {
        //获取短信发送成功返回
        if (loginInfo.status === LOGIN_REQ_SUCCESS) {
            console.log("Login-登录成功")
            console.log(loginInfo)
            //关闭loading
            setMaskVisible(false)

            //查询用户状态
            getUserStateInfo()

        } else if (loginInfo.status === LOGIN_REQ_FAIL) {
            //关闭loading
            setMaskVisible(false)
        }
    }, [loginInfo])

    useEffect(() => {
        console.log("LOGIN-待等用户流程信息返回")
        console.log(userStateInfo)
        if (userStateInfo.status === LOGIN_USER_STATE_REQ_SUCCESS) {
            //关闭loading
            setMaskVisible(false)

            console.log("LOGIN-再次查询user state:")
            console.log("LOGIN-applyStatus: " + userStateInfo.applyStatus)
            console.log("LOGIN-orderStatus: " + userStateInfo.orderStatus)

            //是否为审核中
            const isHomeReviewing = isLoanReviewing(userStateInfo.applyStatus)
            //是否为拒绝
            const isHomeReject = isLoanReject(userStateInfo.applyStatus, userStateInfo.orderStatus)
            //是否为放款中
            const isHomeLoaning = isLoanLoaning(userStateInfo.orderStatus)
            //是否为待还款
            const isHomeRepay = isLoanRepayNow(userStateInfo.orderStatus)
            //是否为待进件
            const isHomeNotLoan = ((!isHomeReviewing) && (!isHomeReject) && (!isHomeLoaning) && (!isHomeRepay))
            console.log("LOGIN-isHomeReviewing: " + isHomeReviewing)
            console.log("LOGIN-isHomeReject: " + isHomeReject)
            console.log("LOGIN-isHomeLoaning: " + isHomeLoaning)
            console.log("LOGIN-isHomeRepay: " + isHomeRepay)
            console.log("LOGIN-isHomeNotLoan: " + isHomeNotLoan)

            //页面转发
            setTimeout(() => {
                if (isHomeReviewing) {
                    history.replace('/review')
                } else if (isHomeReject) {
                    history.replace('/reject')
                } else if (isHomeLoaning) {
                    history.replace('/loaning')
                } else if (isHomeRepay) {
                    history.replace('/repay')
                } else {
                    history.replace('/home')
                }
            }, 500)
        } else if (userStateInfo.status === LOGIN_USER_STATE_REQ_SUCCESS) {
            //关闭loading
            setMaskVisible(false)
        }
    }, [userStateInfo])

    // Formik 表单对象
    const form = useFormik({
        //设置表单初始值
        initialValues: {
            mobile: '',
            code: ''
        },

        //提交
        onSubmit: values => {
            console.log(values)

            //提交登录
            onLoginSubmit()
        },

        //校验
        validate(values) {
            const errors = {}
            if (!values.mobile) {
                errors.mobile = "phone number can't be none"
            }
            if (!values.code) {
                errors.code = "otp can't be none"
            }

            return errors
        }
    })

    //获取用户流程信息
    const getUserStateInfo = () => {
        console.log("LOGIN-获取用户流程信息=====")
        try {
            //显示loading
            setMaskVisible(true)

            //获取Action
            const action = getUserState(PageTag.LOGIN)

            //触发接口
            dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    //请求短信接口
    const doSendOtp = async (mobile) => {
        console.log("doSendOtp: " + mobile);
        try {
            //显示loading
            setMaskVisible(true)

            //获取Action -- 暂时关闭
            // const pageType = isRegitsterType ? "REGPAGE" : "LOGINPAGE"
            const pageType = ""
            const action = sendOtp(mobile, pageType)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    //请求登录接口
    const doOtpLogin = async (mobile, code, directLoginFlag = "NO") => {
        console.log("doLogin: " + mobile + " , " + code);

        try {
            //显示loading
            setMaskVisible(true)

            //获取Action
            const action = doLogin(mobile, code, directLoginFlag)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    //打点接口
    const doHitEvent = async (type, remark = "") => {
        console.log("doHitEvent: " + type + " , " + remark);

        try {
            //获取Action
            const action = saveEvent(type, remark)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    //点击获取otp
    const onSendSmsCode = async () => {
        //验证是否在倒计时中
        //打点
        doHitEvent("LOGIN_OTP_CLICK")

        //验证手机号
        let mobile = form.values.mobile
        if (mobile.length < 9) {
            form.setTouched({ mobile: true })
            return
        }

        //请求发送短信
        doSendOtp(mobile)
    }

    //点击登录
    const onLoginSubmit = async () => {
        try {
            //打点
            doHitEvent("LOGIN_COMMIT_CLICK")

            //验证手机号
            let mobile = form.values.mobile

            //验证验证码
            let code = form.values.code

            //请求登录
            doOtpLogin(mobile, code, "NO")

        } catch (e) {
            console.log(e)
        }
    }

    // 转登录弹框--点击确定
    const onHandleToLoginPageMaskConfirm = () => {
        setNeedToRegisterPage(false)
        setNeedToLoginPage(false)
        history.goBack()
    }

    // 转注册弹框--点击确定
    const onHandleToRegisterPageMaskConfirm = () => {
        setNeedToRegisterPage(false)
        setNeedToLoginPage(false)
        history.goBack()
    }

    // 点击add home监听
    const onHandleAddToHome = (type) => {
        console.log(`点击add home监听: ${type}`)
        if (type === 'home') {
            AddHomeEvent.onHandleAddHomeEventClick()
        } else {
            AddHomeEvent.onHandleAddFavoriteEventClick()
        }
    }

    // 关闭add home
    const onHandleAddToHomeClose = () => {
        console.log(`点击close add home监听`)
        setAddHomeMaskVisible(false)
    }

    return (
        <div className="loginAdRoot">
            {/* 顶部背景 */}
            <div className="loginAdTopBackground">
                <img className="loginAdTopImage" src={icon_home_top_bg} alt="" />
            </div>
            <NavigateBar theme="transparent" showLogout={false} onAddFavorite={() => { setAddHomeMaskIsHomeMode(false); setAddHomeMaskVisible(true) }} onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }}>Nuts Cash</NavigateBar>

            <div className="loginAdAmountContent loginAdMarginTop24Px">

                <img className="loginAdLogoImage" src={icon_home_logo} alt="" />

                <div className="loginAdAmountTitle">Nuts cash</div>

                <div className="loginAdAmountTips">{'Simple, fast and safe personal\ninstant loan service'}</div>

                <div className="loginAdCardContent loginAdMarginTop24Px">
                    <div className="loginAdSliderContent">
                        <div className="contentRowStart">
                            <div className="loginAdSlideStartEdge"></div>
                            <div className="loginAdSliderTitle homeTitleFontBold">How much money do you need</div>
                        </div>

                        <div className="contentRowStart">
                            <div className="loginAdSlideAmountContent">
                                <div className="loginAdSlideRowCenter">
                                    <div className="loginAdSliderTitle homeTitleFont12Px homeMarginRight4Px">XAF</div>
                                    <div className="loginAdSliderTitle homeTitleFont24Px homeTitleFontBold">130,000</div>
                                </div>
                                <div className="loginAdSliderTitle homeTitleFont12Px homeTitleColrTips homeTitleAlignCenter homeInsideTopEdge">Loan amount</div>
                            </div>

                            <div className="loginAdSlideAmountContent">
                                <div className="loginAdSlideRowCenter">
                                    <div className="loginAdSliderTitle homeTitleFont24Px homeTitleColorGreen homeMarginRight4Px homeTitleFontBold">10%</div>
                                    <div className="loginAdSliderTitle homeTitleFont12Px">(per annual)</div>
                                </div>
                                <div className="loginAdSliderTitle homeTitleFont12Px homeTitleColrTips homeTitleAlignCenter homeInsideTopEdge">Interest rate</div>
                            </div>
                        </div>

                        <div className="loginAdSlideRowTracker">
                            <input className="loginAdSlideTracker" type="range" min={0} max={100} value={100} disabled />
                        </div>

                        <div className="loginAdSlideRowAmountRange">
                            <div className="loginAdSlideMinAmount">XAF 50,000</div>
                            <div className="loginAdSlideMaxAmount">XAF 130,000</div>
                        </div>
                    </div>
                </div>

                {/* 输入框 */}
                <div className="loginAdCardContent loginAdMarginTop16Px">
                    <div className="loginAdSliderContent">
                        <div className="contentRowStart">
                            <div className="loginAdSlideStartEdge"></div>
                            <div className="loginAdSliderTitle homeTitleFontBold">Sign up to apply for your loan</div>
                        </div>

                        <form className="pageContentColumn loginAdMarginTop16Px loginAdPaddingHor14Px" onSubmit={form.handleSubmit}>
                            {/* 手机号码输入框 */}
                            <div className="loginAdVerifyInput">
                                <Input
                                    title="Enter your mobile number"
                                    name="mobile"
                                    placeholder="Enter"
                                    type="text"
                                    value={form.values.mobile}
                                    onBlur={form.handleBlur}
                                    onChange={form.handleChange}
                                    autoComplete="off" />
                            </div>
                            {form.errors.mobile && form.touched.mobile && (
                                <div className="validate">{form.errors.mobile}</div>
                            )}

                            <div className="loginAdVerifyInput loginAdMarginTop14Px">
                                {/* 验证码输入框 */}
                                <OtpInput
                                    title="Please enter the verification code"
                                    name="code"
                                    placeholder="Enter"
                                    maxLength={6}
                                    type="text"
                                    value={form.values.code}
                                    onChange={form.handleChange}
                                    onBlur={form.handleBlur}
                                    onClickCallback={onSendSmsCode}
                                    canStart={canStart}
                                    autoComplete="off" />
                            </div>
                            {form.errors.code && form.touched.code && (
                                <div className="validate">{form.errors.code}</div>
                            )}
                        </form>

                        {/* 登录提交 */}
                        <div className="loginAdSubmitContent" onClick={form.handleSubmit}>
                            <div className="loginAdSubmit">Sign up</div>
                        </div>
                    </div>
                </div>
            </div>

            <div className="contentColumnCenter homeRowTopEdge contentHorizontalPadding contentVerticalPadding">
                <div className="loginAdTitleRow">
                    <img className="loginAdTitleImage" src={icon_home_arrow_left} alt="" />
                    <span className="loginAdHeaderTitle homeTitleAlignCenter">Why choose Cash loan</span>
                    <img className="loginAdTitleImage" src={icon_home_arrow_right} alt="" />
                </div>

                <div className="contentRowStart homeInsideTopEdge homeIncreaseContent contentHorizontalPadding">
                    <img className="loginAdStepImage" src={icon_home_increase1} alt="" />
                    <span className="loginAdIncreaseTitle">High amount and reasonable interest.</span>
                </div>

                <div className="contentRowStart homeInsideTopEdge homeInsideTopEdge homeIncreaseContent contentHorizontalPadding">
                    <img className="loginAdStepImage" src={icon_home_increase2} alt="" />
                    <span className="loginAdIncreaseTitle">{'No credit check ,no app, 3 minutes\nget loan.'}</span>
                </div>

                <div className="contentRowStart homeInsideTopEdge homeInsideTopEdge homeIncreaseContent contentHorizontalPadding">
                    <img className="loginAdStepImage" src={icon_home_increase3} alt="" />
                    <span className="loginAdIncreaseTitle">{'With continuous use, loan amount\nincreases rapidly.'}</span>
                </div>
            </div>

            {/* add home gif dialog */}
            <AddToHomeGifDialog visible={addHomeMaskVisible} onConfirm={onHandleAddToHome} onClose={onHandleAddToHomeClose} isHomeMode={addHomeMaskIsHomeMode} />

            <Mask visible={maskVisible} opacity={0.1}
                onMaskClick={() => { }}>
                <div className="overlayContent">
                    <span style={{ fontSize: 24, color: '#ff3141' }} >
                        <DotLoading color="currentColor" />
                    </span>
                </div>
            </Mask>

            {/* {linkUrl &&
                <iframe
                    id="linkFrame"
                    src={linkUrl}
                    width="800"
                    height="600"
                    title="Link"
                    onLoad={onHandleUserLink}
                ></iframe>} */}
        </div>
    )
}